﻿using System.Collections.ObjectModel;
using Caliburn.Micro;
using Serialization;
using Wulong.Phone.Qiushi.Models;

namespace Wulong.Phone.Qiushi.ViewModels
{
    public class QiushiListViewModelStorage : StorageHandler<QiushiListViewModel>
    {
        public override void Configure()
        {
            Id(x => x.Section);
            Property(x => x.Section).InPhoneState().RestoreAfterViewReady();
            Property(x => x.Page).InPhoneState().RestoreAfterViewReady();
            Property(x => x.CanLoadMore).InPhoneState().RestoreAfterViewReady();
            AddInstruction().Configure(x=>
                                           {
                                               x.Key = "qiushi";

                                               x.Save = (instance, getKey, mode) =>
                                                         {
                                                             var value = SilverlightSerializer.Serialize(instance._qiushiItems);
                                                             x.StorageMechanism.Store(getKey(), value);
                                                         };
                                               x.Restore = (instance, getKey, mode) =>
                                                        {
                                                            object value;
                                                            var key = getKey();

                                                            if (x.StorageMechanism.TryGet(key, out value))
                                                            {
                                                                instance._qiushiItems = (value == null)
                                                                                            ? null
                                                                                            : SilverlightSerializer.
                                                                                                  Deserialize(
                                                                                                      (byte[]) value) as ObservableCollection<QiushiItem>;

                                                                x.StorageMechanism.Delete(key);
                                                            }

                                                        };
                                           }).InPhoneState().RestoreAfterViewReady();
        }
    }
}
